package com.wu.store.controller;

import com.wu.store.annotation.CurrentUser;
import com.wu.store.common.util.MessageEntity;
import com.wu.store.entity.Cart;
import com.wu.store.entity.User;
import com.wu.store.service.CartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

	@Autowired
	private CartService cartService;

	@RequestMapping("/count")
	public MessageEntity count(@CurrentUser User user) {
		return new MessageEntity.Builder().success(true).data(cartService.count(user.getId())).create();
	}

	@RequestMapping("/list")
	public MessageEntity list(@CurrentUser User user) {
		return new MessageEntity.Builder().success(true).message("获取成功").data(cartService.list(user.getId())).create();
	}

	@RequestMapping("/save")
	public MessageEntity save(@CurrentUser User user, Cart cart) throws Exception {
		if (cart.getId() == null) {
			cart.setUid(user.getId());
		}
		cartService.save(cart);
		return new MessageEntity.Builder().success(true).message("操作成功").create();
	}

	@RequestMapping("/delete")
	public MessageEntity delete(@CurrentUser User user, Cart cart) throws Exception {
		if (cart.getId() == null) {
			throw new Exception("id必需");
		}
		cart.setUid(user.getId());
		return new MessageEntity.Builder().success(cartService.delete(cart)).message("删除成功").create();
	}

	@RequestMapping("/batchDelete")
	public MessageEntity batchDelete(@CurrentUser User user, String ids) throws Exception {
		if (StringUtils.isEmpty(ids)) {
			throw new Exception("ids必需");
		}
		String[] split = StringUtils.split(ids, ",");
		List<Long> idList = new ArrayList<>();
		for (String idStr : split) {
			idList.add(Long.parseLong(idStr));
		}
		return new MessageEntity.Builder().success(cartService.batchDelete(user.getId(), idList)).message("删除成功").create();
	}
}
